home *** CD-ROM | disk | FTP | other *** search
/ Aminet 2 / Aminet AMIGA CDROM (1994)(Walnut Creek)[Feb 1994][W.O. 44790-1].iso / Aminet / util / cli / UnixUtils.lha / UnixUtils / Source / head.c < prev    next >
Encoding:
C/C++ Source or Header  |  1992-01-02  |  1.7 KB  |  84 lines

  1. /*--------------------------------------------------*
  2.  | Head.c - Unix-like utility.                      |
  3.  | Syntax: head [-N] [file [file [ ... ] ]          |
  4.  | Prints on stdout the first N (default: N_DEFVAL) |
  5.  | lines read from the given files, or from stdin.  |
  6.  | v1.00 MLO 911223                                 |
  7.  *--------------------------------------------------*/
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <ctype.h>
  12. #include "mlo.h"
  13.  
  14. #define N_DEFVAL      10
  15. #define LINE_LENGTH   256
  16.  
  17. void DoTheStuff(FILE *fp, int n);
  18. void Syntax(void);
  19.  
  20. void main(
  21.   int argc,
  22.   char **argv
  23. ){
  24.   int nLines = N_DEFVAL;
  25.  
  26.   while (--argc) {
  27.     if ( ((*++argv)[0] == '-') ) {
  28.       if (isdigit((*argv)[1])) {
  29.         if ((nLines = atoi(*argv+1)) < 1) Syntax();
  30.       } else {
  31.         Syntax();
  32.       }
  33.     } else if ((*argv)[0] == '?') {
  34.       Syntax();
  35.     } else {
  36.       break;
  37.     }
  38.   }
  39.  
  40.   if (argc) {
  41.     while (argc--) {
  42.       FILE *fp;
  43.  
  44.       if ((fp = fopen(*argv, "r")) == NULL) {
  45.         printf("head: couldn't open file \"%s\".\n", *argv);
  46.       } else {
  47.         DoTheStuff(fp, nLines);
  48.         fclose(fp);
  49.       }
  50.       ++argv;
  51.     }
  52.   } else {
  53.     DoTheStuff(stdin, nLines);
  54.   }
  55.  
  56.   exit(SYS_NORMAL_CODE);
  57. }
  58.  
  59. void DoTheStuff(
  60.   FILE *fp,
  61.   int n
  62. ){
  63.   char line[LINE_LENGTH];
  64.  
  65.   while (n--) {
  66.     if (fgets(line, LINE_LENGTH, fp)) {
  67.       fputs(line, stdout);
  68.     } else {
  69.       puts("END-OF-FILE");
  70.       break;
  71.     }
  72.   }
  73. }
  74.  
  75. void Syntax(void)
  76. {
  77.   puts("\nUsage:   head [-N] [file [file [ ... ]]]");
  78.   printf("Purpose: prints on stdout the first N (default: %d) lines read\n",
  79.          N_DEFVAL);
  80.   puts("         from the given file(s), or from stdin.\n");
  81.  
  82.   exit(SYS_NORMAL_CODE);
  83. }
  84.